package ${packageName}.tenant;

import ${packageName}.config.TenantSecurityProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 租户解析过滤器，统一从请求中提取租户信息。
 */
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
@Slf4j
public class TenantFilter extends OncePerRequestFilter {

    private final TenantSecurityProperties securityProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            String tenantId = resolveTenantId(request);
            TenantContext.setTenantId(tenantId);
            filterChain.doFilter(request, response);
        } finally {
            TenantContext.clear();
        }
    }

    private String resolveTenantId(HttpServletRequest request) {
        String headerName = securityProperties.getTenantHeader();
        String tenantFromHeader = request.getHeader(headerName);
        if (StringUtils.hasText(tenantFromHeader)) {
            return tenantFromHeader.trim();
        }
        String defaultTenant = Optional.ofNullable(securityProperties.getTenants())
            .flatMap(tenants -> tenants.stream()
                .map(TenantSecurityProperties.Tenant::getTenantId)
                .filter(StringUtils::hasText)
                .findFirst())
            .orElse("${securityDefaultTenant}");
        log.debug("请求头缺少租户信息，使用默认租户: {}", defaultTenant);
        return defaultTenant;
    }
}
